#include "manage_recordinfo.h"
#include "ui_manage_recordinfo.h"

manage_recordinfo::manage_recordinfo(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::manage_recordinfo)
{
    ui->setupUi(this);

    createModel();

    appDir = QCoreApplication::applicationDirPath();
}

/* 管理员界面关闭，清空所有信息 */
void manage_recordinfo::clearAll()
{
    ui->le_stuName->clear();

    clearView();
}

void manage_recordinfo::on_findBtn_clicked()
{
    clearView();

    QString stuName = ui->le_stuName->text();

    QFile file(appDir + "/" + stuName + ".txt");
    if (file.exists() == false)
    {
        qDebug() << "创建stuName文件" << endl;
    }

    file.open(QIODevice::ReadOnly);

    int lineCount = 0;
    char lineBuf[128] = {0};    //读取内容缓存区域
    while (file.atEnd() == false) // 逐行读取文件内容并计数
    {
        file.readLine(lineBuf, sizeof(lineBuf));
        QString data = lineBuf;

        /* 添加一行 */
        int row = model->rowCount();
        model->insertRow(row);  // 插入新的一行

        // 单独设置每个单元格的数据
        QString bookname = data.split("+")[0];
        QStandardItem *booknameItem = new QStandardItem(bookname);
        model->setItem(row, 0, booknameItem);

        QString author = data.split("+")[1].split("\n")[0];
        QStandardItem *authorItem = new QStandardItem(author);
        model->setItem(row, 1, authorItem);

        lineCount++;
    }
    file.close();
}

/* 创建模型 */
void manage_recordinfo::createModel()
{
    model = new QStandardItemModel(0, 2);
    model->setHorizontalHeaderItem(0, new QStandardItem("书名"));
    model->setHorizontalHeaderItem(1, new QStandardItem("作者"));

    ui->tableView->setModel(model);
    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
}

/* 清空表格数据 */
void manage_recordinfo::clearView()
{
    int rowCount = model->rowCount();
    int columnCount = model->columnCount();

    // 清除所有单元格的内容
    for (int row = 0; row < rowCount; ++row)
    {
        for (int col = 0; col < columnCount; ++col)
        {
            if (model->item(row, col))
            {
                model->setItem(row, col, new QStandardItem());
            }
        }
    }

    // 如果有必要，可以调整行数到零
    model->setRowCount(0);
}

manage_recordinfo::~manage_recordinfo()
{
    delete ui;
}
